#!/bin/bash
# * =====================================================
# * Copyright © hk. 2022-2025. All rights reserved.
# * File name  : 1.sh
# * Author     : 苏木
# * Date       : 2024-09-18
# * ======================================================
##

BLACK="\033[1;30m"
RED='\033[1;31m'    # 红
GREEN='\033[1;32m'  # 绿
YELLOW='\033[1;33m' # 黄
BLUE='\033[1;34m'   # 蓝
PINK='\033[1;35m'   # 紫
CYAN='\033[1;36m'   # 青
WHITE='\033[1;37m'  # 白
CLS='\033[0m'       # 清除颜色

INFO="${GREEN}[INFO]${CLS}"
WARN="${YELLOW}[WARN]${CLS}"
ERR="${RED}[ERR ]${CLS}"

SCRIPT_NAME=${0#*/}
SCRIPT_CURRENT_PATH=${0%/*}
SCRIPT_ABSOLUTE_PATH=`cd $(dirname ${0}); pwd`

SYSTEM_ENVIRONMENT_FILE=/etc/profile # 系统环境变量位置
USER_ENVIRONMENT_FILE=~/.bashrc
SOFTWARE_DIR_PATH=~/2software        # 软件安装目录

TIME_START=
TIME_END=
RK_BUILD_SCRIPT_GIT_REPO_PATH=/home/sumu/8linux-shell-script/compile/rk3568

#===============================================
function get_start_time()
{
	TIME_START=$(date +'%Y-%m-%d %H:%M:%S')
}
function get_end_time()
{
	TIME_END=$(date +'%Y-%m-%d %H:%M:%S')
}

function get_execute_time()
{
	start_seconds=$(date --date="$TIME_START" +%s);
	end_seconds=$(date --date="$TIME_END" +%s);
	duration=`echo $(($(date +%s -d "${TIME_END}") - $(date +%s -d "${TIME_START}"))) | awk '{t=split("60 s 60 m 24 h 999 d",a);for(n=1;n<t;n+=2){if($1==0)break;s=$1%a[n]a[n+1]s;$1=int($1/a[n])}print s}'`
	echo "===*** 运行时间：$((end_seconds-start_seconds))s,time diff: ${duration} ***==="
}

function script_save_to_git_repo()
{
    echo -e "${PINK}current path                 :$(pwd)${CLS}"
    echo -e "${PINK}RK_BUILD_SCRIPT_GIT_REPO_PATH:${RK_BUILD_SCRIPT_GIT_REPO_PATH}${CLS}"
	if [ ! -d ${SHELL_SCRIPT_GIT_REPO_PATH} ];then
		mkdir -pv ${RK_BUILD_SCRIPT_GIT_REPO_PATH}
	fi
    cp -pvf ${SCRIPT_NAME} ${RK_BUILD_SCRIPT_GIT_REPO_PATH}

}
function get_ubuntu_info()
{
    # 获取内核版本信息
    local kernel_version=$(uname -r) # -a选项会获得更详细的版本信息
    # 获取Ubuntu版本信息
    local ubuntu_version=$(lsb_release -ds)

    # 获取Ubuntu RAM大小
    local ubuntu_ram_total=$(cat /proc/meminfo |grep 'MemTotal' |awk -F : '{print $2}' |sed 's/^[ \t]*//g')
    # 获取Ubuntu 交换空间swap大小
    local ubuntu_swap_total=$(cat /proc/meminfo |grep 'SwapTotal' |awk -F : '{print $2}' |sed 's/^[ \t]*//g')
    #显示硬盘，以及大小
    #local ubuntu_disk=$(sudo fdisk -l |grep 'Disk' |awk -F , '{print $1}' | sed 's/Disk identifier.*//g' | sed '/^$/d')
    
    #cpu型号
    local ubuntu_cpu=$(grep 'model name' /proc/cpuinfo |uniq |awk -F : '{print $2}' |sed 's/^[ \t]*//g' |sed 's/ \+/ /g')
    #物理cpu个数
    local ubuntu_physical_id=$(grep 'physical id' /proc/cpuinfo |sort |uniq |wc -l)
    #物理cpu内核数
    local ubuntu_cpu_cores=$(grep 'cpu cores' /proc/cpuinfo |uniq |awk -F : '{print $2}' |sed 's/^[ \t]*//g')
    #逻辑cpu个数(线程数)
    local ubuntu_processor=$(grep 'processor' /proc/cpuinfo |sort |uniq |wc -l)
    #查看CPU当前运行模式是64位还是32位
    local ubuntu_cpu_mode=$(getconf LONG_BIT)

    # 打印结果
    echo "ubuntu: $ubuntu_version - $ubuntu_cpu_mode"
    echo "kernel: $kernel_version"
    echo "ram   : $ubuntu_ram_total"
    echo "swap  : $ubuntu_swap_total"
    echo "cpu   : $ubuntu_cpu,physical id is$ubuntu_physical_id,cores is $ubuntu_cpu_cores,processor is $ubuntu_processor"
}
#===============================================
# 开发环境信息
function dev_env_info()
{
    echo "Development environment: "
    echo "ubuntu : 20.04.2-64(1核12线程 16GB RAM,512GB SSD)"
    echo "VMware : VMware® Workstation 17 Pro 17.6.0 build-24238078"
    echo "Windows: "
    echo "          处理器 AMD Ryzen 7 5800H with Radeon Graphics 3.20 GHz 8核16线程"
    echo "          RAM	32.0 GB (31.9 GB 可用)"
    echo "          系统类型	64 位操作系统, 基于 x64 的处理器"
    echo "说明: 初次安装完SDK,在以上环境下编译大约需要3小时,不加任何修改进行编译大约需要10~15分钟左右"
}

# 要安装的依赖项列表
ANDROID11_DEPENDENCIES=(
    gnupg flex bison gperf build-essential zip curl zlib1g-dev gcc-multilib
    g++-multilib libc6-dev-i386 lib32ncurses5-dev libx11-dev lib32z-dev ccache libgl1-mesa-dev
    libxml2-utils xsltproc unzip python-pyelftools python3-pyelftools device-tree-compiler libfdt-dev
    libfdt1 libssl-dev liblz4-tool python-dev libncurses5 make
)
function amend_python_version
{
    echo -e ${INFO}"修改默认python版本..."
    sudo rm -rf /usr/bin/python
    sudo ln -s /usr/bin/python2 /usr/bin/python
    echo -e ${INFO}"修改完毕，当前默认python版本为："
    python -V
}
# 检查并安装依赖项的函数
function auto_install_dependencies() 
{
    echo -e "${PINK}current path          :$(pwd)${CLS}"
    echo -e "${PINK}ANDROID11_DEPENDENCIES:(共${#ANDROID11_DEPENDENCIES[*]}个)${CLS}"
    echo -e "${ANDROID11_DEPENDENCIES[@]}"

    read -p "是否进行安装?(默认选择继续,退出请输入n):" ret
    if [ "${ret}" != "n" ];then
		get_start_time
        local first_failed_dependencies=()
        #local not_install_dependencies=() # 未安装的依赖
        local installed_dependencies=()   # 已安装的依赖
        for tmp in "${ANDROID11_DEPENDENCIES[@]}"; 
            do
                if ! dpkg -s ${tmp} &>/dev/null; then
                    echo -e ${WARN}"${tmp}未安装,开始安装..."
                    if ! sudo apt-get install -y $tmp; then
                        echo "第一次安装失败: $tmp"
                        first_failed_dependencies+=("$tmp")
                    fi
                    #not_install_dependencies[${#not_install_dependencies[*]}]=${tmp}
                else
                    #echo -e ${INFO}"${tmp}已安装..."
                    installed_dependencies+=("${tmp}")
                    #installed_dependencies[${#installed_dependencies[*]}]=${tmp}
                fi
            done
        echo -e ${INFO}"已安装的依赖(${#installed_dependencies[*]}个)如下："
        echo -e ${installed_dependencies[@]}

        # 尝试重新安装失败的依赖项
        if [ ${#first_failed_dependencies[@]} -gt 0 ]; then
            echo -e ${INFO}"尝试重新安装失败的依赖项..."
            local second_failed_dependencies=()
            for tmp in "${first_failed_dependencies[@]}";
                do
                    if ! sudo apt-get install -y ${tmp}; then
                        echo -e ${WARN}"${tmp}第二次安装失败..."
                        second_failed_dependencies+=($tmp)
                    fi
                done

            if [ ${#second_failed_dependencies[@]} -gt 0 ]; then
                echo -e ${WARN}"以下依赖项安装失败，但将其视为成功: ${second_failed_dependencies[*]}"
            else
                echo -e  ${INFO}"所有依赖项已成功安装。"
            fi
        else
            echo -e ${INFO}"所有依赖项已成功安装。"
        fi

        read -p "是否进行再执行一遍安装程序以确保无误?(默认选择不执行,执行请输入y):" ret
        if [ "${ret}" == "y" ];then
            sudo apt-get install -y ${ANDROID11_DEPENDENCIES[@]}
            #sudo apt-get install -y git-core gnupg flex bison gperf build-essential zip curl zlib1g-dev gcc-multilib \
            #                        g++-multilib libc6-dev-i386 lib32ncurses5-dev libx11-dev lib32z-dev ccache libgl1-mesa-dev \
            #                        libxml2-utils xsltproc unzip python-pyelftools python3-pyelftools device-tree-compiler libfdt-dev \
            #                        libfdt1 libssl-dev liblz4-tool python-dev libncurses5 make
        fi
        amend_python_version

        get_end_time
		get_execute_time
    else
        exit 1
    fi
}
#===============================================
# 【野火——鲁班猫2】
LUBANCAT2_WORK_PATH=/home/sumu/6RK3568/lubancat2
LUBANCAT2_SDK_DIR_NAME=Android11
LUBANCAT2_SDK_PACK_PATH=${LUBANCAT2_WORK_PATH}/${LUBANCAT2_SDK_DIR_NAME}
LUBANCAT2_SDK_PATH=${LUBANCAT2_WORK_PATH}/${LUBANCAT2_SDK_DIR_NAME}/android11-dev
LUBANCAT2_BUILD_TMP_FILE_NAME=build-LubanCat-RK3568.sh
LUBANCAT2_BUILD_FILE_NAME=build.sh
LUBANCAT2_BOARD_NAME="rk3568_lubancat_2_v2_mipi1080p-userdebug"   # 50. rk3568_lubancat_2_hdmi-user
                                            # 51. rk3568_lubancat_2_hdmi-userdebug
                                            # 52. rk3568_lubancat_2_mipi1080p-user
                                            # 53. rk3568_lubancat_2_mipi1080p-userdebug
                                            # 54. rk3568_lubancat_2_mipi600p-user
                                            # 55. rk3568_lubancat_2_mipi600p-userdebug
                                            # 56. rk3568_lubancat_2_mipi800p-user
                                            # 57. rk3568_lubancat_2_mipi800p-userdebug
                                            # 58. rk3568_lubancat_2_v2_hdmi-user
                                            # 59. rk3568_lubancat_2_v2_hdmi-userdebug
                                            # 60. rk3568_lubancat_2_v2_mipi1080p-user
                                            # 61. rk3568_lubancat_2_v2_mipi1080p-userdebug
                                            # 62. rk3568_lubancat_2_v2_mipi600p-user
                                            # 63. rk3568_lubancat_2_v2_mipi600p-userdebug
                                            # 64. rk3568_lubancat_2_v2_mipi800p-user
                                            # 65. rk3568_lubancat_2_v2_mipi800p-userdebug
function lubancat2_sdk_install()
{
    cd  ${LUBANCAT2_SDK_PACK_PATH}
    echo -e "${PINK}current path             :$(pwd)${CLS}"
    echo -e "${PINK}LUBANCAT2_WORK_PATH      :${LUBANCAT2_WORK_PATH}${CLS}"
    echo -e "${PINK}LUBANCAT2_SDK_PACK_PATH  :${LUBANCAT2_SDK_PACK_PATH}${CLS}"
    echo -e "${PINK}LUBANCAT2_SDK_PATH       :${LUBANCAT2_SDK_PATH}${CLS}"
    echo -e "${PINK}LUBANCAT2_BUILD_TMP_FILE :${RK_BUILD_SCRIPT_GIT_REPO_PATH}/${LUBANCAT2_BUILD_TMP_FILE_NAME}${CLS}"
    echo -e "${PINK}LUBANCAT2_BUILD_FILE     :${LUBANCAT2_SDK_PATH}/${LUBANCAT2_BUILD_FILE_NAME}${CLS}"
    
    read -p "是否进行安装?(默认选择继续,不需要请输入n):" ret
    if [ "${ret}" != "n" ];then
        get_start_time
        echo -e ${INFO}"开始解压SDK..."
		cat android*.tar.gza* | tar -xzv
        echo -e ${INFO}"解压完毕!"
        echo -e ${INFO}"修改编译脚本(修改线程数为12)..."
        cp -pvf ${RK_BUILD_SCRIPT_GIT_REPO_PATH}/${LUBANCAT2_BUILD_TMP_FILE_NAME} ${LUBANCAT2_SDK_PATH}/${LUBANCAT2_BUILD_FILE_NAME}
        get_end_time
		get_execute_time
    fi
}
function lubancat2_sdk_build()
{
    cd ${LUBANCAT2_SDK_PATH}

    echo -e "${PINK}current path             :$(pwd)${CLS}"
    echo -e "${PINK}LUBANCAT2_WORK_PATH      :${LUBANCAT2_WORK_PATH}${CLS}"
    echo -e "${PINK}LUBANCAT2_SDK_PACK_PATH  :${LUBANCAT2_SDK_PACK_PATH}${CLS}"
    echo -e "${PINK}LUBANCAT2_SDK_PATH       :${LUBANCAT2_SDK_PATH}${CLS}"
    echo -e "${PINK}LUBANCAT2_BUILD_TMP_FILE :${RK_BUILD_SCRIPT_GIT_REPO_PATH}/${LUBANCAT2_BUILD_FILE}${CLS}"
    echo -e "${PINK}LUBANCAT2_BUILD_FILE_NAME:${LUBANCAT2_BUILD_FILE_NAME}${CLS}"

    read -p "是否进行全编译?(默认选择继续,不需要请输入n):" ret
    if [ "${ret}" != "n" ];then
        get_start_time
        echo -e ${INFO}"开始编译SDK..."
        source build/envsetup.sh
        lunch ${LUBANCAT2_BOARD_NAME}
        ./build.sh -UKAu
        echo -e ${INFO}"编译完毕!"
        get_end_time
		get_execute_time
    fi
}
#===============================================
# 打印菜单
function echo_menu()
{
	echo "================================================="
	echo -e "${GREEN}               RK Build ${CLS}"
	echo -e "${GREEN}                by @苏木${CLS}"
	echo -e "${GREEN}${UBUNTU_VER}@${UBUNTU_KERNEL_VER}${CLS}"
	echo "================================================="
	echo -e "${PINK}current path         :$(pwd)${CLS}"
	echo -e "${PINK}SCRIPT_ABSOLUTE_PATH :${SCRIPT_ABSOLUTE_PATH}${CLS}"
	echo ""
	echo -e "${GREEN} *[0]${CLS} auto_install_dependencies"
	echo -e "${GREEN} *[1]${CLS} dev_env_info"
	echo -e "${GREEN} *[2]${CLS} get_ubuntu_info"
	echo -e "${GREEN} *[3]${CLS} "
	echo -e "${GREEN} *[4]${CLS} 拷贝编译脚本到shell-script仓库进行备份"
	echo -e "${GREEN} *[5]${CLS} 鲁班猫2——lubancat2_sdk_install"
	echo -e "${GREEN} *[6]${CLS} 鲁班猫2——lubancat2_sdk_build"
	echo ""
	echo "================================================="
}
function func_process()
{
	read -p "请选择功能，默认选择退出:" choose
	case "${choose}" in
		"0") auto_install_dependencies;;
		"1") dev_env_info;;  # 编译环境信息
		"2") get_ubuntu_info;;
		"3") ;;
		"4") script_save_to_git_repo;;
		"5") lubancat2_sdk_install;;
		"6") lubancat2_sdk_build;;
		*)  exit 1;;
	esac
}
# 功能实现
get_ubuntu_info # 获取ubuntu信息
echo_menu
func_process